package com.tpyule.tpclass.web.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tpyule.tpclass.entity.bean.FailResultBean;
import com.tpyule.tpclass.entity.bean.ResultBean;
import com.tpyule.tpclass.entity.bean.SuccessResultBean;
import com.tpyule.tpclass.entity.bo.*;
import com.tpyule.tpclass.entity.dto.*;
import com.tpyule.tpclass.entity.pojo.Approve;
import com.tpyule.tpclass.entity.pojo.Record;
import com.tpyule.tpclass.entity.pojo.User;
import com.tpyule.tpclass.service.NotifyService;
import com.tpyule.tpclass.service.RecordService;
import com.tpyule.tpclass.service.RoleService;
import com.tpyule.tpclass.service.UserService;
import com.tpyule.tpclass.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zzz
 * @date 2020/2/21 0021 下午 4:36
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    UserService userService;

    @Autowired
    RecordService recordService;

    @Autowired
    NotifyService notifyService;
    @Autowired
    RoleService roleService;

    /**
     * 根据邮箱或者手机号获取用户
     * @param request
     * @param response
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public void getUser(HttpServletRequest request, HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        String phone=request.getParameter("phone");
        String email=request.getParameter("email");
       /* String msg= phone==null?email:phone;
        User account=userService.getUserByPhoneOrEmail(request.getParameter("email"));

        ResultBean<User> resultBean=new ResultBean<>(account);
        try {
            this.setAjaxResponseResult(response,resultBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            UserBo accountEntity=objectMapper.readValue(request.getParameter("accountData"), UserBo.class);
            if(accountEntity!=null){
                UserBo account=userService.getUserByPhoneOrEmail(accountEntity.getEmail());
                if (account != null) {
                    if(accountEntity.getPassword().equals(account.getPassword())){
                        //request.getSession().setAttribute("account",account);
                        resultBean.setSuccess(true);
                        resultBean.setResult(account.getUser_id());
                        resultBean.setMsg("登陆成功！");
                        resultBean.setCode(200);
                    }else{
                        resultBean.setSuccess(false);
                        resultBean.setMsg("账号或密码错误");
                        resultBean.setCode(403);
                    }
                }else {
                    resultBean.setSuccess(false);
                    resultBean.setMsg("账号不存在");
                    resultBean.setCode(404);
                }
            }else{
                resultBean.setSuccess(false);
                resultBean.setMsg("程序错误，请联系管理员！");
                resultBean.setCode(500);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            resultBean.setSuccess(false);
            resultBean.setMsg("程序错误，请联系管理员！");
            resultBean.setCode(501);
        }finally {
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

    @RequestMapping("/login")
    @ResponseBody
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            User user = new User();
            String userStr=request.getParameter("userData");
            UserDto userDto=objectMapper.readValue(userStr, UserDto.class);
            if(userDto.getUsername().indexOf("@")!=-1){
                user.setPhone(userDto.getUsername());
            }else {
                user.setEmail(userDto.getUsername());
            }
            user.setPassword(userDto.getPassword());
            User oldUser=userService.getUserByPhoneOrEmail(user.getPhone()==null?user.getEmail():user.getPhone());
            if(oldUser!=null){
                String encodePassword=MD5Util.getMd5(user.getPassword()+oldUser.getSalt(),2);
                if(oldUser.getPassword().equals(encodePassword)){
                    UserShowBo bo = getUserShowBo(oldUser);
                    resultBean=new SuccessResultBean<>(bo,"登陆成功");
                    String recordStr = request.getParameter("recordData");
                    if (recordStr!=null){
                        Record record = objectMapper.readValue(recordStr,Record.class);
                        record.setUserId(oldUser.getUserId());
                        if(record.getIp()!=null&&record.getIp().length()>0)
                            recordService.addRecord(record);
                        notifyService.pullAnnounce(oldUser);
                    }
                }else{
                    resultBean=new FailResultBean<User>(user,"密码错误");
                }
            }else{
                resultBean=new FailResultBean<>("该用户不存在");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            String userId=request.getParameter("userId");
            User user = userService.getUserById(userId);
            if(user!=null){
                    UserShowBo bo = getUserShowBo(user);
                    resultBean=new SuccessResultBean<>(bo,"成功");
            }else{
                resultBean=new FailResultBean<>("数据错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public void registerUser(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String userStr=request.getParameter("userData");
            User user=objectMapper.readValue(userStr, User.class);
            User oldUser=userService.getUserByPhoneOrEmail(user.getPhone()==null?user.getEmail():user.getPhone());
            if(oldUser!=null){
                 resultBean=new FailResultBean<String>("不存在","该用户已存在");
            }else{
                userService.addUser(user);
                    resultBean=new SuccessResultBean<User>(user,"注册成功");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/update")
    @ResponseBody
    public void updateUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            String userStr=request.getParameter("userData");
            User user=objectMapper.readValue(userStr, User.class);
            Boolean result = userService.updateUser(user);
            if(result){
                resultBean=new SuccessResultBean<User>(user,"更新成功");
            }else{
                resultBean=new FailResultBean<>("更新失败");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/userBinding")
    @ResponseBody
    public void userBinding(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            String userStr=request.getParameter("userData");
            UserBindDto user=objectMapper.readValue(userStr, UserBindDto.class);
            resultBean = userService.userBindingUpdate(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getNewUser")
    @ResponseBody
    public void getNewUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            int day =Integer.parseInt(request.getParameter("day"));
            if (day>0){

                List<NewUserBo> users = userService.getNewUser(day);
                if(users!=null){
                    resultBean = new SuccessResultBean(users,"成功");
                }else {
                    resultBean = new FailResultBean("失败！");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getSizeUser")
    @ResponseBody
    public void getSizeUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String queryData = request.getParameter("queryData");
            if (queryData!=null){
                UserListQueryDto dto = objectMapper.readValue(queryData, UserListQueryDto.class);
                if(dto!=null){
                   int result = userService.getSizeUser(dto);
                   resultBean = new SuccessResultBean(result, "成功！");
                }else {
                    resultBean = new FailResultBean("数据错误！");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean(500,"系统异常");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getListUser")
    @ResponseBody
    public void getListUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String queryData = request.getParameter("queryData");
            if (queryData!=null){
                UserListQueryDto dto = objectMapper.readValue(queryData, UserListQueryDto.class);
                if(dto!=null){
                    List<UserListBo> bos = userService.getListUser(dto);
                    if (bos!=null){
                        resultBean = new SuccessResultBean(bos, "成功！");
                    }else {
                        resultBean = new FailResultBean("失败！");
                    }
                }else {
                    resultBean = new FailResultBean("数据错误！");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping("/getAnaUser")
    @ResponseBody
    public void getAnaUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String queryData = request.getParameter("queryData");
            if (queryData!=null){
                StudentQueryDto dto = objectMapper.readValue(queryData, StudentQueryDto.class);
                if(dto!=null){
                    List<StudentAnaBo> bos = userService.getAnaUser(dto);
                    if (bos!=null){
                        resultBean = new SuccessResultBean(bos, "成功！");
                    }else {
                        resultBean = new FailResultBean("失败！");
                    }
                }else {
                    resultBean = new FailResultBean("数据错误！");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getSizeAnaUser")
    @ResponseBody
    public void getSizeAnaUser(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String queryData = request.getParameter("queryData");
            if (queryData!=null){
                StudentQueryDto dto = objectMapper.readValue(queryData, StudentQueryDto.class);
                if(dto!=null){
                    int result = userService.getSizeAnaUser(dto);
                    resultBean = new SuccessResultBean(result, "成功！");
                }else {
                    resultBean = new FailResultBean("数据错误！");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping("/getDetailById")
    @ResponseBody
    public void getDetailById(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String userId = request.getParameter("userId");
            if (userId!=null){
                UserDetailBo bo = userService.getDetailUser(userId);
                if (bo!=null){
                    resultBean = new SuccessResultBean(bo,"成功");
                }else {
                    resultBean = new FailResultBean("未找到该用户");
                }
            } else {
                resultBean = new FailResultBean("数据错误！");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean(500,"系统异常");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/resetPassword")
    @ResponseBody
    public void resetPassword(HttpServletRequest request,HttpServletResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;

        try {
            String userStr=request.getParameter("userData");
            User user=objectMapper.readValue(userStr, User.class);
            int result = userService.resetPassword(user);
            if(result!=-1){
                resultBean=new SuccessResultBean<User>(user,"更新成功");
            }else{
                resultBean=new FailResultBean<>("更新失败");
            }
        } catch (JsonProcessingException e) {
            resultBean=new FailResultBean<>("系统异常");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/addApprove")
    @ResponseBody
    public void addApprove(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String approveData=request.getParameter("approveData");
            Approve approve=objectMapper.readValue(approveData, Approve.class);
            if(approve!=null){
                int result = userService.addApprove(approve);
                if (result!=0){
                    resultBean=new SuccessResultBean("成功");
                } else {
                    resultBean = new FailResultBean("失败");
                }
            }else{
                resultBean = new FailResultBean("数据异常");
            }
        } catch (JsonProcessingException e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/updateApprove")
    @ResponseBody
    public void updateApprove(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String approveData=request.getParameter("approveData");
            Approve approve=objectMapper.readValue(approveData, Approve.class);
            if(approve!=null){
                int result = userService.updateApprove(approve);
                if (result!=0){
                    resultBean=new SuccessResultBean("成功");
                } else {
                    resultBean = new FailResultBean("失败");
                }
            }else{
                resultBean = new FailResultBean("数据异常");
            }
        } catch (JsonProcessingException e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getListApprove")
    @ResponseBody
    public void getListApprove(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String queryData=request.getParameter("queryData");
            if (queryData!=null) {
                CommonQueryDto dto = objectMapper.readValue(queryData, CommonQueryDto.class);
                if (dto != null) {
                    List<ApproveListBo> bos = userService.getListApprove(dto);
                    if (bos != null) {
                        resultBean = new SuccessResultBean(bos, "成功");
                    } else {
                        resultBean = new FailResultBean("失败");
                    }
                } else {
                    resultBean = new FailResultBean("数据异常");
                }
            }else {
                resultBean = new FailResultBean("数据异常");
            }
        } catch (JsonProcessingException e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getSizeApprove")
    @ResponseBody
    public void getSizeApprove(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            int result = userService.getSizeApprove();
            resultBean = new SuccessResultBean(result,"成功");
        } catch (Exception e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getDetailApprove")
    @ResponseBody
    public void getDetailApprove(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String approveId=request.getParameter("approveId");
            if (approveId!=null) {
                int aid = Integer.parseInt(approveId);
                ApproveDetailBo bo = userService.getDetailApprove(aid);
                resultBean = new SuccessResultBean(bo,"成功");
            }else {
                resultBean = new FailResultBean("数据异常");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/getDetailApproveByUId")
    @ResponseBody
    public void getDetailApproveByUId(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            String userId=request.getParameter("userId");
            if (userId!=null) {
                ApproveDetailBo bo = userService.getDetailApproveByUId(userId);
                resultBean = new SuccessResultBean(bo,"成功");
            }else {
                resultBean = new FailResultBean("数据异常");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getAnaSex")
    @ResponseBody
    public void getAnaSex(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            List<AnaBoTwo> anaBoTwos = userService.getAnaSex();
            if (anaBoTwos!=null) {
                resultBean = new SuccessResultBean(anaBoTwos,"成功");
            }else {
                resultBean = new FailResultBean("数据异常");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getAnaOffice")
    @ResponseBody
    public void getAnaOffice(HttpServletRequest request,HttpServletResponse response){
        ObjectMapper objectMapper=new ObjectMapper();
        ResultBean resultBean=null;
        try {
            List<AnaBoTwo> anaBoTwos = userService.getAnaOffice();
            if (anaBoTwos!=null) {
                resultBean = new SuccessResultBean(anaBoTwos,"成功");
            }else {
                resultBean = new FailResultBean("数据异常");
            }
        } catch (Exception e) {
            resultBean = new FailResultBean("系统错误");
        }finally{
            try {
                this.setAjaxResponseResult(response,resultBean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public UserShowBo getUserShowBo(User user){

        UserShowBo bo = null;
        if (user!=null){
             bo = new UserShowBo();
             bo.setUserId(user.getUserId());
             bo.setPhone(user.getPhone());
             bo.setEmail(user.getEmail());
             bo.setNickname(user.getNickname());
             bo.setImageUrl(user.getImageUrl());
             bo.setSignature(user.getSignature());
             bo.setGender(user.getGender());
             bo.setOffice(user.getOffice());
             bo.setCreateTime(user.getCreateTime());
        }
        return bo;
    }

}
